using LitJson;
namespace CGF
{
    public partial class PanelDeviceIncomeDetail : UIComponentBase, IAwake<UILayer, bool>, IDestroy
    {
        private string year, month, day;

        public static void Open(string year, string month, string day)
        {
            UIManagerComponent.instance.OpenUI<PanelDeviceIncomeDetail>(UILayer.Normal, RootComponent.instance, false).SetInfo(year, month, day);
        }

        public static void Close()
        {
            UIManagerComponent.instance.CloseUI<PanelDeviceIncomeDetail>();
        }

        public async void Awake(UILayer layer, bool isFloat)
        {
            await SpawnPrefab("Prefabs/GameUI/PanelDeviceIncomeDetail", layer, isFloat);
            BindProperties(transform);
            
            BtnBack.SetClick(Close);

            Curr.text = I18N.Currency;
            TitleSub.text = "";

            if (year != null)
            {
                SetInfo(year, month, day);
            }
        }

        private void SetInfo(string year, string month, string day)
        {
            this.year = year;
            this.month = month;
            this.day = day;
            if (!Curr) return;

            string dateStr = $"{month}/{day}";
            if (CGFConfig.Instance.ReleaseArea != EArea.China)
            {
                dateStr = $"{day}/{month}";
            }
            Title.text = I18N_title.Replace("{date}", dateStr);

            string api = $"/v1/earnings/detail?date={year}-{month}-{day}";
            string listKey = "";
            Table.Column[] columns =
            {
                (cell, data) => data["bot_id"].ToString(),
                (cell, data) => data["product_num"].ToString(),
                (cell, data) => $"<color={Config.NumColor}>{I18N.Currency}<b>{StringHelper.Format2Decimal((int)data["total_amount"] * 0.01f)}</b></color>",
            };
            Table.GetComponent<Table>().ReqData(api, listKey, columns, null, null, null, res =>
            {
                int totalDevices = 0;
                int totalAmount = 0;
                JsonData cellData = res.jsonData["data"];
                for (int i = 0; i < cellData.Count; i++)
                {
                    JsonData data = cellData[i];
                    totalDevices += 1;
                    totalAmount += (int)data["total_amount"];
                }
                TitleSub.text = I18N_title_sub.Replace("{num}", totalDevices.ToString()).Replace("{amount}", $"{I18N.Currency} {StringHelper.Format2Decimal(totalAmount * 0.01f)}");
            });
        }

        public override void OnDestroy()
        {
            base.OnDestroy();
        }

    }
}
